package io;

import atom.UnaryAtom;
import formula.BinaryFormula;
import formula.Formula;
import formula.UnaryFormula;
import literal.UnaryLiteral;
import sign.FormulaSign;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class InputFrame extends JFrame {

    private JTextField inputField; // 输入框
    private JTextArea textArea;    // 显示历史输入
    //private boolean running = true; // 控制循环的标志
    //private static ArrayList<Formula> conditions=new ArrayList<>();

    public InputFrame() {
        setTitle("用户输入示例");
        setSize(400, 300);
        setLocationRelativeTo(null);//居中显示
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());//默认块状布局

        // 创建输入框
        inputField = new JTextField();//获取每次输入
        textArea = new JTextArea();//用户输入内容展示
        textArea.setEditable(false); // 设置文本域不可编辑

        // 将文本区域放入滚动面板
        JScrollPane scrollPane = new JScrollPane(textArea);

        // 添加组件到窗口
        add(scrollPane, BorderLayout.CENTER);
        add(inputField, BorderLayout.SOUTH);

        // 监听输入框的回车事件
        inputField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int len;
                ArrayList<Formula> conditions=new ArrayList<>();
                String userInput = inputField.getText().trim(); // 获取用户输入
                textArea.append("用户输入: " + userInput + "\n"); // 显示到文本区域

                if ("exit".equalsIgnoreCase(userInput)) { // 检查用户是否输入了"exit"
                    //running = false;
                    textArea.append("输入结束，禁止输入");
                    inputField.setEnabled(false); // 禁用输入框
                    //System.exit(0); // 退出程序
                }

                len=userInput.length();
                //len=0时如何处理，需要稍后实现
                if(len==0){
                    textArea.append("Input is null,input again!"+"\n");
                }
//                else if (len==1){//Unary literal with no negated
//                    conditions.add(create_uf(userInput));//创建uf并添加到conditions中
 //               }
                else if (len==5 && userInput.startsWith("not")){//Unary literal with negated (not p)
                    conditions.add(create_negated_uf(userInput));
                }else {//此时输入大概率为binary formula（也有可能是0/null）
                    // 调用检测和分离 not 的方法（似乎没用到not方法）
                    //String notResult = detectAndSplitNot(userInput);

                    //exist+any method
                    ArrayList<String> existResult = detectAndSplitExist(userInput);//经过正则表达式整理后返回的列表
                    ArrayList<String> anyResult = detectAndSplitAny(userInput);
                    // 显示匹配结果
                    // 如果检测到 not，显示分离结果
//                    if (!notResult.isEmpty()) {
//                        textArea.append(notResult + "\n");
//                    }
                    if (!existResult.isEmpty()) {//检测到exist，输入以exist开头
                        //textArea.append(existResult + "\n");
                        conditions.add(create_exist_bf(existResult));
                    }

                    if (!anyResult.isEmpty()) {
                        //textArea.append(anyResult + "\n");
                        conditions.add(create_any_bf(anyResult));
                    }

                }
                inputField.setText(""); // 清空输入框

                for (Formula condition:conditions) {
                    System.out.println(condition.toString());

                }
                //System.out.println("");

            }
        });

        setVisible(true);
    }

    /**
     * 检测用户输入是否包含 "not"，如果包含则分离 "not" 和其后续内容
     * @param input 用户输入的字符串
     * @return 分离后的字符串，如果没有匹配到 "not" 则返回空字符串
     */
    private String detectAndSplitNot(String input) {
        // 定义正则表达式来匹配"not"及其后续内容
        Pattern pattern = Pattern.compile("(not)(.*)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(input);

        if (matcher.matches()) {
            String notPart = matcher.group(1);       // 匹配到的 "not"
            String afterNotPart = matcher.group(2);  // 匹配到的 "not" 后续内容

            // 返回分离结果
            return "匹配到: \nnot: " + notPart + "\n后续内容: " + afterNotPart;
        }

        // 如果未匹配到 "not"，返回空字符串
        return "";
    }

    /**
     * 检测用户输入是否以 "exist" 开头，并分离开头和后续内容
     * @param input 用户输入的字符串
     * @return 分离后的字符串，如果没有匹配到 "exist" 则返回空字符串
     */
    private ArrayList<String> detectAndSplitExist(String input) {
        ArrayList<String> exist_separate=new ArrayList<>();//用于最后的返回值
        // 正则匹配 "exist" 开头并捕获括号内的内容
        Pattern pattern = Pattern.compile("^(exist)\\(([^,]+),\\s*(.*)\\)$", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(input);

        if (matcher.matches()) {
            String existPart = matcher.group(1);    // "exist"
            String firstPart = matcher.group(2).trim(); // 括号内的第一个部分
            String secondPart = matcher.group(3).trim(); // 括号内的第二个部分

            // 进一步分离第二部分是否包含 "not"
            String firstElement, secondElement;
            if (firstPart.startsWith("not ")) {
                firstElement = "not";
                firstPart = firstPart.substring(4).trim();
            } else {
                firstElement = firstPart;
                firstPart = "";
            }

            if (secondPart.startsWith("not ")) {
                secondElement = "not";
                secondPart = secondPart.substring(4).trim();
            } else {
                secondElement = secondPart;
                secondPart = "";
            }

            // 返回四(五)部分的输出
            //return "匹配到:\nexist: " + existPart + "\nFirst: " + firstElement + "\nSecond: " + firstPart + "\nThird: " + secondElement + "\n";


            exist_separate.add(existPart);
            exist_separate.add(firstElement);
            exist_separate.add(firstPart);
            exist_separate.add(secondElement);
            exist_separate.add(secondPart);


            //return existPart+"\t"+firstElement+"\t"+firstPart+"\t"+secondElement+"\t"+secondPart;
        }
        return exist_separate;
        //return "";
    }

    /**
     * 检测用户输入是否以 "any" 开头，并分离开头和后续内容
     * @param input 用户输入的字符串
     * @return 分离后的字符串，如果没有匹配到 "any" 则返回空字符串
     */
    private ArrayList<String> detectAndSplitAny(String input) {
        ArrayList<String> any_separate=new ArrayList<>();//用于最后的返回值
        // 正则匹配 "any" 开头并捕获括号内的内容
        Pattern pattern = Pattern.compile("^(any)\\(([^,]+),\\s*(.*)\\)$", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(input);

        if (matcher.matches()) {
            String anyPart = matcher.group(1);    // "any"
            String firstPart = matcher.group(2).trim(); // 括号内的第一个部分
            String secondPart = matcher.group(3).trim(); // 括号内的第二个部分

            // 进一步分离第二部分是否包含 "not"
            String firstElement, secondElement;
            if (firstPart.startsWith("not ")) {
                firstElement = "not";
                firstPart = firstPart.substring(4).trim();
            } else {
                firstElement = firstPart;
                firstPart = "";
            }

            if (secondPart.startsWith("not ")) {
                secondElement = "not";
                secondPart = secondPart.substring(4).trim();
            } else {
                secondElement = secondPart;
                secondPart = "";
            }

            // 返回四(五)部分的输出
            //return "匹配到:\nany: " + existPart + "\nFirst: " + firstElement + "\nSecond: " + firstPart + "\nThird: " + secondElement + "\n";
            //return anyPart+"\t"+firstElement+"\t"+firstPart+"\t"+secondElement+"\t"+secondPart;
            any_separate.add(anyPart);
            any_separate.add(firstElement);
            any_separate.add(firstPart);
            any_separate.add(secondElement);
            any_separate.add(secondPart);

        }
        return any_separate;
        //return "";
    }

    public UnaryFormula create_uf(String input){//len(input)=1,此时atom必不带负号，negated=false
        UnaryFormula uf=new UnaryFormula(new UnaryLiteral(new UnaryAtom(input),false));
        return uf;
    }

    public UnaryFormula create_negated_uf(String input){//len(input)=5,此时atom带负号，negated=true
        //注意：此时input=not p,直接放入unary atom。若negated设置为true，则结果为not not p。因此这里negated设置为false
        //虽然从逻辑上来说有问题，但是运行时没问题
        UnaryFormula uf=new UnaryFormula(new UnaryLiteral(new UnaryAtom(input),false));//这个negated未来可能会报错。目前运行正常
        return uf;
    }

    public BinaryFormula create_exist_bf(ArrayList<String> exist_separate){//exist的4种类型配对,传入的数组已经被正则表达式进行配对
        if (exist_separate.get(2).equals("") && exist_separate.get(4).equals("")){//index2,4为空，exist(p,q)
            //bf的例子：BinaryFormula f1=new BinaryFormula(FormulaSign.ANY,q,l);
            UnaryFormula left=new UnaryFormula(new UnaryLiteral(new UnaryAtom(exist_separate.get(1)),false));
            UnaryFormula right=new UnaryFormula(new UnaryLiteral(new UnaryAtom(exist_separate.get(3)),false));
            BinaryFormula bf1=new BinaryFormula(FormulaSign.EXIST,left,right);
            return bf1;
        }else if (exist_separate.get(2).equals("")){//exist(p,not q)
            UnaryFormula left=new UnaryFormula(new UnaryLiteral(new UnaryAtom(exist_separate.get(1)),false));
            UnaryFormula right=new UnaryFormula(new UnaryLiteral(new UnaryAtom(exist_separate.get(4)),true));
            BinaryFormula bf2=new BinaryFormula(FormulaSign.EXIST,left,right);
            return bf2;
        }else if (exist_separate.get(4).equals("")){//exist(not p,q)
            UnaryFormula left=new UnaryFormula(new UnaryLiteral(new UnaryAtom(exist_separate.get(2)),true));
            UnaryFormula right=new UnaryFormula(new UnaryLiteral(new UnaryAtom(exist_separate.get(3)),false));
            BinaryFormula bf3=new BinaryFormula(FormulaSign.EXIST,left,right);
            return bf3;
        }else {//不存在空字符，即exist(not p,not q)
            UnaryFormula left=new UnaryFormula(new UnaryLiteral(new UnaryAtom(exist_separate.get(2)),true));
            UnaryFormula right=new UnaryFormula(new UnaryLiteral(new UnaryAtom(exist_separate.get(4)),true));
            BinaryFormula bf4=new BinaryFormula(FormulaSign.EXIST,left,right);
            return bf4;
        }
    }

    public BinaryFormula create_any_bf(ArrayList<String> any_separate){//exist的4种类型配对,传入的数组已经被正则表达式进行配对
        if (any_separate.get(2).equals("") && any_separate.get(4).equals("")){//index2,4为空，any(p,q)
            //bf的例子：BinaryFormula f1=new BinaryFormula(FormulaSign.ANY,q,l);
            UnaryFormula left=new UnaryFormula(new UnaryLiteral(new UnaryAtom(any_separate.get(1)),false));
            UnaryFormula right=new UnaryFormula(new UnaryLiteral(new UnaryAtom(any_separate.get(3)),false));
            BinaryFormula bf1=new BinaryFormula(FormulaSign.ANY,left,right);
            return bf1;
        }else if (any_separate.get(2).equals("")){//any(p,not q)
            UnaryFormula left=new UnaryFormula(new UnaryLiteral(new UnaryAtom(any_separate.get(1)),false));
            UnaryFormula right=new UnaryFormula(new UnaryLiteral(new UnaryAtom(any_separate.get(4)),true));
            BinaryFormula bf2=new BinaryFormula(FormulaSign.ANY,left,right);
            return bf2;
        }else if (any_separate.get(4).equals("")){//any(not p,q)
            UnaryFormula left=new UnaryFormula(new UnaryLiteral(new UnaryAtom(any_separate.get(2)),true));
            UnaryFormula right=new UnaryFormula(new UnaryLiteral(new UnaryAtom(any_separate.get(3)),false));
            BinaryFormula bf3=new BinaryFormula(FormulaSign.ANY,left,right);
            return bf3;
        }else {//不存在空字符，即any(not p,not q)
            UnaryFormula left=new UnaryFormula(new UnaryLiteral(new UnaryAtom(any_separate.get(2)),true));
            UnaryFormula right=new UnaryFormula(new UnaryLiteral(new UnaryAtom(any_separate.get(4)),true));
            BinaryFormula bf4=new BinaryFormula(FormulaSign.ANY,left,right);
            return bf4;
        }
    }

    /**
     * Returns all formula conditions that have been input.
     * @return List of formulas
     */

//    public static ArrayList<Formula> getConditions(){//尝试返回最终的ArrayList<Formula>
//        return conditions;
//    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new InputFrame();
            }
        });

    }
}
